<template>
  <div>
    <el-upload
      class="upload-demo"
      action=""
      drag
      :auto-upload="false"
      :on-change="uploadChange"
      :limit="1"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import * as XLSX from "xlsx"; // Vue3 版本
const router = useRouter();
const store = useStore();
// 选中文件后执行
const uploadChange = async (e) => {
  console.log(e);
  const files = e.raw;
  if (files.length <= 0) {
    return false;
  } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
    console.log("上传格式不正确，请上传xls或者xlsx格式");
    return false;
  }
  // 读取表格
  const fileReader = new FileReader();
  fileReader.onload = (ev) => {
    const workbook = XLSX.read(ev.target.result, {
      type: "binary",
    });
    const wsname = workbook.SheetNames[0];
    const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
    // console.log(ws); // 转换成json的数据
    const m = dealExcel(ws); // ...对数据进行自己需要的操作
    console.log(m);
    store.dispatch("excelImport",m).then((res) => {
      if(res.code==200){
        router.push("/UserList");
      }
    });
    
  };
  fileReader.readAsBinaryString(files);
};
const dealExcel = (ws) => {
  let keymap = {
    // 我们要转换的开头
    姓名: "username",
    联系方式: "mobile",
    头像: "avatar",
    角色: "role",
    开通时间: "openTime",
  };
  ws.forEach((sourceObj) => {
    let arr = new Array();
    Object.keys(sourceObj).map((keys) => {
      if (keys.includes("步骤")) {
        arr.push(sourceObj[keys]);
        delete sourceObj[keys];
      } else if (keymap[keys]) {
        sourceObj[keymap[keys]] = sourceObj[keys];
        delete sourceObj[keys];
      }
    });
    sourceObj["steps"] = arr;
  });
  return ws;
};
</script>

<style scoped lang='scss'>
</style>